package com.dashu.base.config;

import com.dashu.base.utils.SystemUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.TextUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class ConfigFile {

    protected static Map<String, String> filemap = new HashMap<>();
    private static String api_file_urls = SystemUtils.isOSWindows() ? "C:\\Users\\Administrator\\.m2\\config" : "/config/";

    public ConfigFile(boolean isDebug , String... name){
        this(name);
        if (isDebug){
            log.info("打印:" + filemap.toString());
        }
    }


    public ConfigFile(String... name) {
        try {
            String newName = "";
//          file = new InputStreamReader(new FileInputStream("config"));
//            file = new InputStreamReader(new FileInputStream("/opt/ParkWei/ParkLock/OpenApi/config"));
            if (!SystemUtils.isOSWindows()) {
                if (name == null)
                    newName = "config";
                else if (!TextUtils.isEmpty(name[0]))
                    newName = name[0];
                else
                    newName = "config";
            }

            if (SystemUtils.isOSWindows() && name != null && !TextUtils.isEmpty(name[0])) {
                api_file_urls = "";
                newName = name[0];
            }
            log.info("配置文件:" + api_file_urls + newName);
            InputStreamReader file = new InputStreamReader(new FileInputStream(api_file_urls + newName));
            BufferedReader br = new BufferedReader(file);
            String data = null;
            while ((data = br.readLine()) != null) {
                parse(data);
            }


            //自动刷新
//            configureAndFlush(30 * 60 * 1000);

            file.close();
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private void parse(String line) {
        if (line.trim().startsWith("#")) //以#开头作为注释
            return;
        String[] args = line.split("=");
        if (args.length != 2)
            return;
        String key = args[0].trim();
        String value = args[1].trim();
        filemap.put(key, value);
    }


    public String get(String key) {
        return filemap.get(key);
    }


}
